package cn.tedu.plus.datetime;

import java.util.Calendar;
import java.util.Date;

public class CalendarDemo {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();

        System.out.println(calendar);

        System.out.println();

        //Calendar处理月份是，范围是0-11 5=6
        calendar.set(2020,5,22); //2020-6-22
        System.out.println(calendar);
        System.out.println();

        //修改年（不会自动更新）
        calendar.set(Calendar.YEAR,2009);
        System.out.println(calendar);
        System.out.println();

        //获取值
        int year = calendar.get(Calendar.YEAR);
        System.out.println("年份"+year);
        int month = calendar.get(Calendar.MONTH);
        System.out.println("月份"+month);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println("当月第几天"+dayOfMonth);
        int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
        System.out.println("小时"+hourOfDay);
        int minutes = calendar.get(Calendar.MINUTE);
        System.out.println("分钟"+minutes);
        int second = calendar.get(Calendar.SECOND);
        System.out.println("秒钟"+second);

        System.out.println();

        //增加字段值（会自动更新）
        calendar.add(Calendar.DAY_OF_MONTH,1);//22->23
        System.out.println(calendar);
        System.out.println();

        //month:11=12
        calendar.set(2015,11,30);
        calendar.add(Calendar.DAY_OF_MONTH,5);//2016-1-4
        System.out.println(calendar);
        System.out.println();

        //add负数=减少字段值
        calendar.add(Calendar.DAY_OF_MONTH,-6);//2015-12(11)-29
        System.out.println(calendar);
        System.out.println();

        //对比2个Calendar对象的时间先后  before/after
        //1)2000-5-6 12:34:56
        //2)2021-8-16  11:33:22
        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(2000,5,6,12,34,56);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.set(2021,8,16,11,33,22);

        boolean result = calendar1.before(calendar2);
        System.out.println("1 before 2 ="+result);
        result = calendar1.after(calendar2);
        System.out.println("1 after 2 ="+result);

        System.out.println();

        //getTime转换Date对象
        Date date = calendar1.getTime();
        System.out.println(date);
        //Date转换Calendar对象
        calendar1.setTime(date);
        System.out.println(calendar1);

        System.out.println();

        //getTimeInMills()获取时间戳
        Long s1 = calendar2.getTimeInMillis();
        System.out.println(s1);
        //setTimeInMillis(long mills)设置时间戳
        calendar1.setTimeInMillis(s1);
        System.out.println(calendar1);

    }
}
